#encoding:utf-8
from django.core.mail import send_mail, EmailMessage
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from forms import ContactForm
from settings import email_subject, company_email

def vista(request, template_name='index.html', active='index'):
    return render_to_response(template_name, {'active': active}, context_instance = RequestContext(request))

def contact(request, template_name='contacto.html', active='contacto'):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            telephone = form.cleaned_data['telephone']
            message = form.cleaned_data['message']
            copy = form.cleaned_data['copy']
            message_to_send = render_to_string('email.html', {
                'name': name,
                'email': email,
                'telephone': telephone,
                'message': message})
            if copy:
                to=[company_email, email]
            else :
                to=[company_email]
            try:
                send_mail(subject=email_subject,
                                   message=message_to_send,
                                   from_email=company_email,
                                   recipient_list=to,
                                   fail_silently=False)
                isSend = True
            except:
                isSend = False
            if isSend:
                return render_to_response('index.html', {'active': 'index', 'isSend': isSend}, context_instance = RequestContext(request))
            else :
                form = ContactForm()
                return render_to_response('contacto.html', {'active': 'contacto', 'isSend': isSend, 'form':form}, context_instance = RequestContext(request))
    else:
        form = ContactForm()
    return render_to_response(template_name, {'active': active, 'form': form}, context_instance = RequestContext(request))
